package beautiful.butterfly.schedule.expression;

import com.google.common.base.Preconditions;

import java.io.Serializable;
import java.text.ParseException;

/**
 * Provides a parser and evaluator for unix-like cron expressions. Cron
 * expressions provide the ability to specify complex time combinations such as
 * &quot;At 8:00am every Monday through Friday&quot; or &quot;At 1:30am every
 * last Friday of the month&quot;.
 * <P>
 * Cron expressions are comprised of 6 required fields and one optional field
 * separated by white space. The fields respectively are described as follows:
 * <p>
 * <table cellspacing="8">
 * <tr>
 * <th align="left">Field Name</th>
 * <th align="left">&nbsp;</th>
 * <th align="left">Allowed Values</th>
 * <th align="left">&nbsp;</th>
 * <th align="left">Allowed Special Characters</th>
 * </tr>
 * <tr>
 * <td align="left"><code>Seconds</code></td>
 * <td align="left">&nbsp;</th>
 * <td align="left"><code>0-59</code></td>
 * <td align="left">&nbsp;</th>
 * <td align="left"><code>, - * /</code></td>
 * </tr>
 * <tr>
 * <td align="left"><code>Minutes</code></td>
 * <td align="left">&nbsp;</th>
 * <td align="left"><code>0-59</code></td>
 * <td align="left">&nbsp;</th>
 * <td align="left"><code>, - * /</code></td>
 * </tr>
 * <tr>
 * <td align="left"><code>Hours</code></td>
 * <td align="left">&nbsp;</th>
 * <td align="left"><code>0-23</code></td>
 * <td align="left">&nbsp;</th>
 * <td align="left"><code>, - * /</code></td>
 * </tr>
 * <tr>
 * <td align="left"><code>Day-of-month</code></td>
 * <td align="left">&nbsp;</th>
 * <td align="left"><code>1-31</code></td>
 * <td align="left">&nbsp;</th>
 * <td align="left"><code>, - * ? / L W</code></td>
 * </tr>
 * <tr>
 * <td align="left"><code>Month</code></td>
 * <td align="left">&nbsp;</th>
 * <td align="left"><code>1-12 or JAN-DEC</code></td>
 * <td align="left">&nbsp;</th>
 * <td align="left"><code>, - * /</code></td>
 * </tr>
 * <tr>
 * <td align="left"><code>Day-of-Week</code></td>
 * <td align="left">&nbsp;</th>
 * <td align="left"><code>1-7 or SUN-SAT</code></td>
 * <td align="left">&nbsp;</th>
 * <td align="left"><code>, - * ? / L #</code></td>
 * </tr>
 * <tr>
 * <td align="left"><code>Year (Optional)</code></td>
 * <td align="left">&nbsp;</th>
 * <td align="left"><code>empty, 1970-2199</code></td>
 * <td align="left">&nbsp;</th>
 * <td align="left"><code>, - * /</code></td>
 * </tr>
 * </table>
 * <P>
 * The '*' character is used to specify all values. For example, &quot;*&quot;
 * in the minute field means &quot;every minute&quot;.
 * <P>
 * The '?' character is allowed for the day-of-month and day-of-week fields. It
 * is used to specify 'no specific value'. This is useful when you need to
 * specify something in one of the two fields, but not the other.
 * <P>
 * The '-' character is used to specify ranges For example &quot;10-12&quot; in
 * the hour field means &quot;the hours 10, 11 and 12&quot;.
 * <P>
 * The ',' character is used to specify additional values. For example
 * &quot;MON,WED,FRI&quot; in the day-of-week field means &quot;the days Monday,
 * Wednesday, and Friday&quot;.
 * <P>
 * The '/' character is used to specify increments. For example &quot;0/15&quot;
 * in the seconds field means &quot;the seconds 0, 15, 30, and 45&quot;. And
 * &quot;5/15&quot; in the seconds field means &quot;the seconds 5, 20, 35, and
 * 50&quot;.  Specifying '*' before the  '/' is equivalent to specifying 0 is
 * the value to start with. Essentially, for each field in the expression, there
 * is a set of numbers that can be turned on or off. For seconds and minutes,
 * the numbers range from 0 to 59. For hours 0 to 23, for days of the month 0 to
 * 31, and for months 1 to 12. The &quot;/&quot; character simply helps you turn
 * on every &quot;nth&quot; value in the given set. Thus &quot;7/6&quot; in the
 * month field only turns on month &quot;7&quot;, it does NOT mean every 6th
 * month, please note that subtlety.
 * <P>
 * The 'L' character is allowed for the day-of-month and day-of-week fields.
 * This character is short-hand for &quot;last&quot;, but it has different
 * meaning in each of the two fields. For example, the value &quot;L&quot; in
 * the day-of-month field means &quot;the last day of the month&quot; - day 31
 * for January, day 28 for February on non-leap years. If used in the
 * day-of-week field by itself, it simply means &quot;7&quot; or
 * &quot;SAT&quot;. But if used in the day-of-week field after another value, it
 * means &quot;the last xxx day of the month&quot; - for example &quot;6L&quot;
 * means &quot;the last friday of the month&quot;. When using the 'L' option, it
 * is important not to specify lists, or ranges of values, as you'll get
 * confusing results.
 * <P>
 * The 'W' character is allowed for the day-of-month field.  This character
 * is used to specify the weekday (Monday-Friday) nearest the given day.  As an
 * example, if you were to specify &quot;15W&quot; as the value for the
 * day-of-month field, the meaning is: &quot;the nearest weekday to the 15th of
 * the month&quot;. So if the 15th is a Saturday, the trigger will fire on
 * Friday the 14th. If the 15th is a Sunday, the trigger will fire on Monday the
 * 16th. If the 15th is a Tuesday, then it will fire on Tuesday the 15th.
 * However if you specify &quot;1W&quot; as the value for day-of-month, and the
 * 1st is a Saturday, the trigger will fire on Monday the 3rd, as it will not
 * 'jump' over the boundary of a month's days.  The 'W' character can only be
 * specified when the day-of-month is a single day, not a range or list of days.
 * <P>
 * The 'L' and 'W' characters can also be combined for the day-of-month
 * expression to yield 'LW', which translates to &quot;last weekday of the
 * month&quot;.
 * <P>
 * The '#' character is allowed for the day-of-week field. This character is
 * used to specify &quot;the nth&quot; XXX day of the month. For example, the
 * value of &quot;6#3&quot; in the day-of-week field means the third Friday of
 * the month (day 6 = Friday and &quot;#3&quot; = the 3rd one in the month).
 * Other examples: &quot;2#1&quot; = the first Monday of the month and
 * &quot;4#5&quot; = the fifth Wednesday of the month. Note that if you specify
 * &quot;#5&quot; and there is not 5 of the given day-of-week in the month, then
 * no firing will occur that month.  If the '#' character is used, there can
 * only be one expression in the day-of-week field (&quot;3#1,6#3&quot; is
 * not valid, since there are two expressions).
 * <P>
 * <!--The 'C' character is allowed for the day-of-month and day-of-week fields.
 * This character is short-hand for "calendar". This means values are
 * calculated against the associated calendar, if any. If no calendar is
 * associated, then it is equivalent to having an all-inclusive calendar. A
 * value of "5C" in the day-of-month field means "the first day included by the
 * calendar on or after the 5th". A value of "1C" in the day-of-week field
 * means "the first day included by the calendar on or after Sunday".-->
 * <P>
 * The legal characters and the names of months and days of the week are not
 * case sensitive.
 * <p>
 * <p>
 * <b>NOTES:</b>
 * <ul>
 * <li>Support for specifying both a day-of-week and a day-of-month value is
 * not complete (you'll need to use the '?' character in one of these fields).
 * </li>
 * <li>Overflowing ranges is supported - that is, having a larger number on
 * the left hand side than the right. You might do 22-2 to catch 10 o'clock
 * at night until 2 o'clock in the morning, or you might have NOV-FEB. It is
 * very important to note that overuse of overflowing ranges creates ranges
 * that don't make sense and no effort has been made to determine which
 * interpretation CronExpression chooses. An example would be
 * "0 0 14-6 ? * FRI-MON". </li>
 * </ul>
 * </p>
 */
@SuppressWarnings({"rawtypes", "unchecked"})
public class CronExpression implements Serializable, Cloneable {

    protected static final int second = 0;
    protected static final int minute = 1;
    protected static final int hour = 2;
    protected static final int day_of_month = 3;
    protected static final int month = 4;
    //
    protected static final int day_of_week = 5;
    protected static final int year = 6;
    //
    protected static final int all_spec_int = 99; // '*'
    protected static final int no_spec_int = 98; // '?'
    protected static final Integer all_spec = new Integer(all_spec_int);
    protected static final Integer no_spec = new Integer(no_spec_int);
    protected static final Map dayMap = new HashMap(60);
    protected static final Map monthMap = new HashMap(20);

    protected static final int crontrigger_year_to_giveup_scheduling_at = 2299;
    private static final long serialVersionUID = 12423409423L;

    static {
        monthMap.put("jan", new Integer(0));
        monthMap.put("feb", new Integer(1));
        monthMap.put("mar", new Integer(2));
        monthMap.put("apr", new Integer(3));
        monthMap.put("may", new Integer(4));
        monthMap.put("jun", new Integer(5));
        monthMap.put("jul", new Integer(6));
        monthMap.put("aug", new Integer(7));
        monthMap.put("sep", new Integer(8));
        monthMap.put("oct", new Integer(9));
        monthMap.put("nov", new Integer(10));
        monthMap.put("dec", new Integer(11));

        dayMap.put("sun", new Integer(1));
        dayMap.put("mon", new Integer(2));
        dayMap.put("tue", new Integer(3));
        dayMap.put("wed", new Integer(4));
        dayMap.put("thu", new Integer(5));
        dayMap.put("fri", new Integer(6));
        dayMap.put("sat", new Integer(7));
    }

    protected transient TreeSet seconds;
    protected transient TreeSet minutes;
    protected transient TreeSet hours;
    protected transient TreeSet daysOfMonth;
    protected transient TreeSet months;
    protected transient TreeSet years;
    //
    protected transient TreeSet daysOfWeek;
    //
    protected transient MonLdaySet monLdaySet;
    protected transient boolean lastdayOfWeek = false;
    protected transient int nthdayOfWeek = 0;
    protected transient boolean lastdayOfMonth = false;
    protected transient boolean nearestWeekday = false;
    protected transient boolean expressionParsed = false;
    private String cronExpression = null;


    public CronExpression(String cronExpression) throws ParseException {
        Preconditions.checkNotNull(cronExpression, "cronExpression");
        this.cronExpression = cronExpression;
        buildExpression(this.cronExpression);
    }


    protected void buildExpression(String expression) throws ParseException {
        expressionParsed = true;

        try {

            if (seconds == null) {
                seconds = new TreeSet();
            }
            if (minutes == null) {
                minutes = new TreeSet();
            }
            if (hours == null) {
                hours = new TreeSet();
            }
            if (months == null) {
                months = new TreeSet();
            }
            if (years == null) {
                years = new TreeSet();
            }
            //
            if (daysOfWeek == null) {
                daysOfWeek = new TreeSet();
            }
            if (daysOfMonth == null) {
                daysOfMonth = new TreeSet();
            }
            //
            int type = second;

            StringTokenizer expressionStringTokenizer = new StringTokenizer(expression, " \t", false);
            while (expressionStringTokenizer.hasMoreTokens() && type <= year) {
                String string = expressionStringTokenizer.nextToken().trim();
                //可以允许传入的数据

//                protected static final int second = 0;
//                protected static final int minute = 1;
//                protected static final int hour = 2;
//                protected static final int day_of_month = 3;
//                protected static final int month = 4;
//                //
//                protected static final int day_of_week = 5;
//                protected static final int year = 6;

                if (type == second) {

                } else if (type == minute) {

                } else if (type == hour) {

                } else if (type == day_of_month) {

                } else if (type == month) {

                } else if (type == day_of_week) {

                } else if (type == year) {

                }


                //不支持小写l(L)
                // throw an exception if L is used with other days of the month
                if (type == day_of_month && string.indexOf('L') != -1 && string.length() > 1 && string.indexOf(",") >= 0) {
                    throw new ParseException("Support for specifying 'L' and 'LW' with other days of the month is not implemented", -1);
                }
                // throw an exception if L is used with other days of the week
                if (type == day_of_week && string.indexOf('L') != -1 && string.length() > 1 && string.indexOf(",") >= 0) {
                    throw new ParseException("Support for specifying 'L' with other days of the week is not implemented", -1);
                }

                StringTokenizer stringTokenizer = new StringTokenizer(string, ",");
                while (stringTokenizer.hasMoreTokens()) {
                    String value = stringTokenizer.nextToken();
                    storeExpressionVals(0, value, type);
                }

                type++;
            }//end

            if (type <= day_of_week) {
                throw new ParseException("Unexpected end of expression.",
                        expression.length());
            }

            if (type <= year) {
                storeExpressionVals(0, "*", year);
            }

            TreeSet dow = getSet(day_of_week);
            TreeSet dom = getSet(day_of_month);

            // Copying the logic from the UnsupportedOperationException below
            boolean dayOfMSpec = !dom.contains(no_spec);
            boolean dayOfWSpec = !dow.contains(no_spec);

            if (dayOfMSpec && !dayOfWSpec) {
                // skip
            } else if (dayOfWSpec && !dayOfMSpec) {
                // skip
            } else {
                throw new ParseException(
                        "Support for specifying both a day-of-week AND a day-of-month $parameter is not implemented.",
                        0);
            }
        } catch (ParseException pe) {
            throw pe;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ParseException("Illegal cron expression format ("
                    + e.toString() + ")", 0);
        }
    }

    protected int storeExpressionVals(int index, String string, int type)
            throws ParseException {

        int incr = 0;
        int i = skipWhiteSpace(index, string);
        if (i >= string.length()) {
            return i;
        }
        char c = string.charAt(i);
        if ((c >= 'A') && (c <= 'Z') && (!string.equals("L")) && (!string.equals("LW"))) {
            String sub = string.substring(i, i + 3);
            int sval = -1;
            int eval = -1;
            if (type == month) {
                sval = getMonthNumber(sub) + 1;
                if (sval <= 0) {
                    throw new ParseException("Invalid Month value: '" + sub
                            + "'", i);
                }
                if (string.length() > i + 3) {
                    c = string.charAt(i + 3);
                    if (c == '-') {
                        i += 4;
                        sub = string.substring(i, i + 3);
                        eval = getMonthNumber(sub) + 1;
                        if (eval <= 0) {
                            throw new ParseException("Invalid Month value: '"
                                    + sub + "'", i);
                        }
                    }
                }
            } else if (type == day_of_week) {
                sval = getDayOfWeekNumber(sub);
                if (sval < 0) {
                    throw new ParseException("Invalid Day-of-Week value: '"
                            + sub + "'", i);
                }
                if (string.length() > i + 3) {
                    c = string.charAt(i + 3);
                    if (c == '-') {
                        i += 4;
                        sub = string.substring(i, i + 3);
                        eval = getDayOfWeekNumber(sub);
                        if (eval < 0) {
                            throw new ParseException(
                                    "Invalid Day-of-Week value: '" + sub + "'",
                                    i);
                        }
                    } else if (c == '#') {
                        try {
                            i += 4;
                            nthdayOfWeek = Integer.parseInt(string.substring(i));
                            if (nthdayOfWeek < 1 || nthdayOfWeek > 5) {
                                throw new Exception();
                            }
                        } catch (Exception e) {
                            throw new ParseException(
                                    "A numeric value between 1 and 5 must follow the '#' option",
                                    i);
                        }
                    } else if (c == 'L') {
                        lastdayOfWeek = true;
                        i++;
                    }
                }

            } else {
                throw new ParseException(
                        "Illegal characters for this position: '" + sub + "'",
                        i);
            }
            if (eval != -1) {
                incr = 1;
            }
            addToSet(sval, eval, incr, type);
            return (i + 3);
        }

        if (c == '?') {
            i++;
            if ((i + 1) < string.length()
                    && (string.charAt(i) != ' ' && string.charAt(i + 1) != '\t')) {
                throw new ParseException("Illegal character after '?': "
                        + string.charAt(i), i);
            }
            if (type != day_of_week && type != day_of_month) {
                throw new ParseException(
                        "'?' can only be specfied for Day-of-Month or Day-of-Week.",
                        i);
            }
            if (type == day_of_week && !lastdayOfMonth) {
                if (daysOfMonth.isEmpty()) {
                    addToSet(no_spec_int, -1, 0, type);
                    return i;
                }
                int val = ((Integer) daysOfMonth.last()).intValue();
                if (val == no_spec_int) {
                    throw new ParseException(
                            "'?' can only be specfied for Day-of-Month -OR- Day-of-Week.",
                            i);
                }
            }

            addToSet(no_spec_int, -1, 0, type);
            return i;
        }

        if (c == '*' || c == '/') {
            if (c == '*' && (i + 1) >= string.length()) {
                addToSet(all_spec_int, -1, incr, type);
                return i + 1;
            } else if (c == '/'
                    && ((i + 1) >= string.length() || string.charAt(i + 1) == ' ' || string
                    .charAt(i + 1) == '\t')) {
                throw new ParseException("'/' must be followed by an integer.",
                        i);
            } else if (c == '*') {
                i++;
            }
            c = string.charAt(i);
            if (c == '/') { // is an increment specified?
                i++;
                if (i >= string.length()) {
                    throw new ParseException("Unexpected end of string.", i);
                }

                incr = getNumericValue(string, i);

                i++;
                if (incr > 10) {
                    i++;
                }
                if (incr > 59 && (type == second || type == minute)) {
                    throw new ParseException("Increment > 60 : " + incr, i);
                } else if (incr > 23 && (type == hour)) {
                    throw new ParseException("Increment > 24 : " + incr, i);
                } else if (incr > 31 && (type == day_of_month)) {
                    throw new ParseException("Increment > 31 : " + incr, i);
                } else if (incr > 7 && (type == day_of_week)) {
                    throw new ParseException("Increment > 7 : " + incr, i);
                } else if (incr > 12 && (type == month)) {
                    throw new ParseException("Increment > 12 : " + incr, i);
                }
            } else {
                incr = 1;
            }

            addToSet(all_spec_int, -1, incr, type);
            return i;
        } else if (c == 'L') {
            i++;
            if (type == day_of_month) {
                lastdayOfMonth = true;
            }
            if (type == day_of_week) {
                addToSet(7, 7, 0, type);
            }
            if (type == day_of_month && string.length() > i) {
                c = string.charAt(i);
                if (c == 'W') {
                    nearestWeekday = true;
                    i++;
                }
            }
            return i;
        } else if (c >= '0' && c <= '9') {
            int val = Integer.parseInt(String.valueOf(c));
            i++;
            if (i >= string.length()) {
                addToSet(val, -1, -1, type);
            } else {
                c = string.charAt(i);
                if (c >= '0' && c <= '9') {
                    ValueSet vs = getValue(val, string, i);
                    val = vs.value;
                    i = vs.position;
                }
                i = checkNext(i, string, val, type);
                return i;
            }
        } else {
            throw new ParseException("Unexpected character: " + c, i);
        }

        return i;
    }

    protected int checkNext(int pos, String s, int val, int type)
            throws ParseException {

        int end = -1;
        int i = pos;

        if (i >= s.length()) {
            addToSet(val, end, -1, type);
            return i;
        }

        char c = s.charAt(pos);

        if (c == 'L') {
            if (type == day_of_week) {
                if (val < 1 || val > 7)
                    throw new ParseException(
                            "Day-of-Week values must be between 1 and 7", -1);
                lastdayOfWeek = true;
            } else if (type == day_of_month) {
                //compatible for expression like '2L'
                if (monLdaySet == null) {
                    monLdaySet = new MonLdaySet();
                }
                lastdayOfMonth = true;
                monLdaySet.isLast = true;
                monLdaySet.value = 0;
                monLdaySet.ex = val;
                i++;
                if (i < s.length()) {
                    throw new ParseException("invalid expression or char", i);
                }
                return i;
            } else {
                throw new ParseException("'L' option is not valid here. (position="
                        + i + ")", i);
            }
            TreeSet set = getSet(type);
            set.add(new Integer(val));
            i++;
            return i;
        }

        if (c == 'W') {
            if (type == day_of_month) {
                nearestWeekday = true;
            } else {
                throw new ParseException("'W' option is not valid here. (position="
                        + i + ")", i);
            }
            TreeSet set = getSet(type);
            set.add(new Integer(val));
            i++;
            return i;
        }

        if (c == '#') {
            if (type != day_of_week) {
                throw new ParseException("'#' option is not valid here. (position="
                        + i + ")", i);
            }
            i++;
            try {
                nthdayOfWeek = Integer.parseInt(s.substring(i));
                if (nthdayOfWeek < 1 || nthdayOfWeek > 5) {
                    throw new Exception();
                }
            } catch (Exception e) {
                throw new ParseException(
                        "A numeric value between 1 and 5 must follow the '#' option",
                        i);
            }

            TreeSet set = getSet(type);
            set.add(new Integer(val));
            i++;
            return i;
        }

        if (c == '-') {
            i++;
            c = s.charAt(i);
            //compatible for expression like '5-L'
            if (c == 'L') {
                if (monLdaySet == null) {
                    monLdaySet = new MonLdaySet();
                }
                monLdaySet.isLast = true;
                monLdaySet.value = val;
                monLdaySet.ex = 1;
                i++;
                if (i < s.length()) {
                    throw new ParseException("invalid expression or char", i);
                }
                return i;
            }
            int v = Integer.parseInt(String.valueOf(c));
            end = v;
            i++;
            if (i >= s.length()) {
                addToSet(val, end, 1, type);
                return i;
            }
            c = s.charAt(i);
            if (c >= '0' && c <= '9') {
                ValueSet vs = getValue(v, s, i);
                int v1 = vs.value;
                end = v1;
                i = vs.position;
                //compatible for expression like '5-10L'
                if (i < s.length()) {
                    c = s.charAt(i);
                    if (c == 'L') {
                        if (monLdaySet == null) {
                            monLdaySet = new MonLdaySet();
                        }
                        monLdaySet.isLast = true;
                        monLdaySet.value = val;
                        monLdaySet.ex = v1;
                        i++;
                        if (i < s.length()) {
                            throw new ParseException("invalid expression or char", i);
                        }
                        return i;
                    } else {
                        throw new ParseException("invalid expression or char", i);
                    }
                }
            }
            //compatible for expression like '5-2L'
            if (c == 'L') {
                if (monLdaySet == null) {
                    monLdaySet = new MonLdaySet();
                }
                monLdaySet.isLast = true;
                monLdaySet.value = val;
                monLdaySet.ex = v;
                i++;
                if (i < s.length()) {
                    throw new ParseException("invalid expression or char", i);
                }
                return i;
            }
            if (i < s.length() && ((c = s.charAt(i)) == '/')) {
                i++;
                c = s.charAt(i);
                int v2 = Integer.parseInt(String.valueOf(c));
                i++;
                if (i >= s.length()) {
                    addToSet(val, end, v2, type);
                    return i;
                }
                c = s.charAt(i);
                if (c >= '0' && c <= '9') {
                    ValueSet vs = getValue(v2, s, i);
                    int v3 = vs.value;
                    addToSet(val, end, v3, type);
                    i = vs.position;
                    return i;
                } else {
                    addToSet(val, end, v2, type);
                    return i;
                }
            } else {
                addToSet(val, end, 1, type);
                return i;
            }
        }

        if (c == '/') {
            i++;
            c = s.charAt(i);
            int v2 = Integer.parseInt(String.valueOf(c));
            i++;
            if (i >= s.length()) {
                addToSet(val, end, v2, type);
                return i;
            }
            c = s.charAt(i);
            if (c >= '0' && c <= '9') {
                ValueSet vs = getValue(v2, s, i);
                int v3 = vs.value;
                addToSet(val, end, v3, type);
                i = vs.position;
                return i;
            } else {
                throw new ParseException("Unexpected character '" + c
                        + "' after '/'", i);
            }
        }

        addToSet(val, end, 0, type);
        i++;
        return i;
    }


    protected int skipWhiteSpace(int index, String string) {
        for (; index < string.length() && (string.charAt(index) == ' '); index++)//只支持空格不支持其他
        {
            ;
        }

        return index;
    }

    protected int findNextWhiteSpace(int i, String s) {
        for (; i < s.length() && (s.charAt(i) != ' ' || s.charAt(i) != '\t'); i++) {
            ;
        }

        return i;
    }

    protected void addToSet(int val, int end, int incr, int type)
            throws ParseException {

        TreeSet set = getSet(type);

        if (type == second || type == minute) {
            if ((val < 0 || val > 59 || end > 59) && (val != all_spec_int)) {
                throw new ParseException(
                        "Minute and Second values must be between 0 and 59", -1);
            }
        } else if (type == hour) {
            if ((val < 0 || val > 23 || end > 23) && (val != all_spec_int)) {
                throw new ParseException(
                        "Hour values must be between 0 and 23", -1);
            }
        } else if (type == day_of_month) {
            if ((val < 1 || val > 31 || end > 31) && (val != all_spec_int)
                    && (val != no_spec_int)) {
                throw new ParseException(
                        "Day of month values must be between 1 and 31", -1);
            }
        } else if (type == month) {
            if ((val < 1 || val > 12 || end > 12) && (val != all_spec_int)) {
                throw new ParseException(
                        "Month values must be between 1 and 12", -1);
            }
        } else if (type == day_of_week) {
            if ((val == 0 || val > 7 || end > 7) && (val != all_spec_int)
                    && (val != no_spec_int)) {
                throw new ParseException(
                        "Day-of-Week values must be between 1 and 7", -1);
            }
        }

        if ((incr == 0 || incr == -1) && val != all_spec_int) {
            if (val != -1) {
                set.add(new Integer(val));
            } else {
                set.add(no_spec);
            }

            return;
        }

        int startAt = val;
        int stopAt = end;

        if (val == all_spec_int && incr <= 0) {
            incr = 1;
            set.add(all_spec); // put in a marker, but also fill values
        }

        if (type == second || type == minute) {
            if (stopAt == -1) {
                stopAt = 59;
            }
            if (startAt == -1 || startAt == all_spec_int) {
                startAt = 0;
            }
        } else if (type == hour) {
            if (stopAt == -1) {
                stopAt = 23;
            }
            if (startAt == -1 || startAt == all_spec_int) {
                startAt = 0;
            }
        } else if (type == day_of_month) {
            if (stopAt == -1) {
                stopAt = 31;
            }
            if (startAt == -1 || startAt == all_spec_int) {
                startAt = 1;
            }
        } else if (type == month) {
            if (stopAt == -1) {
                stopAt = 12;
            }
            if (startAt == -1 || startAt == all_spec_int) {
                startAt = 1;
            }
        } else if (type == day_of_week) {
            if (stopAt == -1) {
                stopAt = 7;
            }
            if (startAt == -1 || startAt == all_spec_int) {
                startAt = 1;
            }
        } else if (type == year) {
            if (stopAt == -1) {
                stopAt = crontrigger_year_to_giveup_scheduling_at;
            }
            if (startAt == -1 || startAt == all_spec_int) {
                startAt = 1970;
            }
        }

        // if the end of the range is before the start, then we need to overflow into
        // the next day, month etc. This is done by adding the maximum amount for that
        // type, and using modulus max to determine the value being added.
        int max = -1;
        if (stopAt < startAt) {
            switch (type) {
                case second:
                    max = 60;
                    break;
                case minute:
                    max = 60;
                    break;
                case hour:
                    max = 24;
                    break;
                case month:
                    max = 12;
                    break;
                case day_of_week:
                    max = 7;
                    break;
                case day_of_month:
                    max = 31;
                    break;
                case year:
                    throw new IllegalArgumentException(
                            "Start year must be less than stop year");
                default:
                    throw new IllegalArgumentException(
                            "Unexpected type encountered");
            }
            stopAt += max;
        }

        for (int i = startAt; i <= stopAt; i += incr) {
            if (max == -1) {
                // ie: there's no max to overflow over
                set.add(new Integer(i));
            } else {
                // take the modulus to get the real value
                int i2 = i % max;

                // 1-indexed ranges should not include 0, and should include their max
                if (i2 == 0
                        && (type == month || type == day_of_week || type == day_of_month)) {
                    i2 = max;
                }

                set.add(new Integer(i2));
            }
        }
    }

    protected TreeSet getSet(int type) {
        switch (type) {
            case second:
                return seconds;
            case minute:
                return minutes;
            case hour:
                return hours;
            case day_of_month:
                return daysOfMonth;
            case month:
                return months;
            case day_of_week:
                return daysOfWeek;
            case year:
                return years;
            default:
                return null;
        }
    }

    protected ValueSet getValue(int v, String s, int i) {
        char c = s.charAt(i);
        String s1 = String.valueOf(v);
        while (c >= '0' && c <= '9') {
            s1 += c;
            i++;
            if (i >= s.length()) {
                break;
            }
            c = s.charAt(i);
        }
        ValueSet val = new ValueSet();

        val.position = (i < s.length()) ? i : i + 1;
        val.value = Integer.parseInt(s1);
        return val;
    }

    protected int getNumericValue(String s, int i) {
        int endOfVal = findNextWhiteSpace(i, s);
        String val = s.substring(i, endOfVal);
        return Integer.parseInt(val);
    }

    protected int getMonthNumber(String s) {
        Integer integer = (Integer) monthMap.get(s);

        if (integer == null) {
            return -1;
        }

        return integer.intValue();
    }

    protected int getDayOfWeekNumber(String string) {
        Integer integer = (Integer) dayMap.get(string);

        if (integer == null) {
            return -1;
        }

        return integer.intValue();
    }

    /**
     * Returns the next date/time <I>after</I> the given date/time which
     * satisfies the cron expression.
     *
     * @param date the date/time at which to begin the search for the next valid
     *             date/time
     * @return the next valid date/time
     */
    public Date getNextTimeAfter(Date date) {
        return getDateTimeAfter(date);
    }

    protected Date getDateTimeAfter(Date afterTime) {


        Calendar calendar1 = Calendar.getInstance();

        // move ahead one second, since we're computing the time *after* the
        // given time
        afterTime = new Date(afterTime.getTime() + 1000);
        // CronTrigger does not deal with milliseconds
        calendar1.setTime(afterTime);
        calendar1.set(Calendar.MILLISECOND, 0);//不支持毫秒
        boolean endDaysFlag = false;
        boolean gotOne = false;
        // loop until we've computed the next time, or we've past the endTime
        while (!gotOne) {

            //if (endTime != null && cl.getTime().after(endTime)) return null;
            if (calendar1.get(Calendar.YEAR) > 2100)//不要太久 我活不到那么久
            { // prevent endless loop...
                return null;
            }
            int second = calendar1.get(Calendar.SECOND);
            int minute = calendar1.get(Calendar.MINUTE);

            // get second.................................................
            SortedSet sortedSet = seconds.tailSet(new Integer(second));
            if (sortedSet != null && sortedSet.size() != 0) {
                second = ((Integer) sortedSet.first()).intValue();
            } else {
                second = ((Integer) seconds.first()).intValue();
                minute++;
                calendar1.set(Calendar.MINUTE, minute);
            }
            calendar1.set(Calendar.SECOND, second);

            minute = calendar1.get(Calendar.MINUTE);
            int hourOfDay = calendar1.get(Calendar.HOUR_OF_DAY);
            int $ = -1;//临时值

            // get minute.................................................
            //tailSet(E fromElement) 方法用来返回这个集合，其元素大于或等于fromElement的部分视图。
            sortedSet = minutes.tailSet(new Integer(minute));
            if (sortedSet != null && sortedSet.size() != 0) {
                $ = minute;
                minute = ((Integer) sortedSet.first()).intValue();
            } else {
                minute = ((Integer) minutes.first()).intValue();
                hourOfDay++;
            }
            if (minute != $) {
                calendar1.set(Calendar.SECOND, 0);
                calendar1.set(Calendar.MINUTE, minute);
                setCalendarHour(calendar1, hourOfDay);
                continue;
            }
            calendar1.set(Calendar.MINUTE, minute);

            hourOfDay = calendar1.get(Calendar.HOUR_OF_DAY);
            int dayOfMonth = calendar1.get(Calendar.DAY_OF_MONTH);
            $ = -1;

            // get hour
            sortedSet = hours.tailSet(new Integer(hourOfDay));
            if (sortedSet != null && sortedSet.size() != 0) {
                $ = hourOfDay;
                hourOfDay = ((Integer) sortedSet.first()).intValue();
            } else {
                hourOfDay = ((Integer) hours.first()).intValue();
                dayOfMonth++;
            }
            if (hourOfDay != $) {
                calendar1.set(Calendar.SECOND, 0);
                calendar1.set(Calendar.MINUTE, 0);
                calendar1.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                setCalendarHour(calendar1, hourOfDay);
                continue;
            }
            calendar1.set(Calendar.HOUR_OF_DAY, hourOfDay);

            dayOfMonth = calendar1.get(Calendar.DAY_OF_MONTH);
            int month = calendar1.get(Calendar.MONTH) + 1;
            // '+ 1' because calendar is 0-based for this field, and we are
            // 1-based
            $ = -1;
            int tmon = month;

            // get day...................................................
            boolean dayOfMSpec = !daysOfMonth.contains(no_spec);
            boolean dayOfWSpec = !daysOfWeek.contains(no_spec);
            if (dayOfMSpec && !dayOfWSpec) { // get day by day of month rule
                int endDays = 0;
                if (monLdaySet != null && monLdaySet.isLast && !endDaysFlag) {
                    int end = getDaySizeOfMonth(calendar1.get(Calendar.YEAR), month)
                            - monLdaySet.ex + 1;
                    if (monLdaySet.value == 0) {
                        endDays = end;
                    } else {
                        try {
                            if (monLdaySet.value > end) {
                                throw new IllegalArgumentException(
                                        "Start day must be less than end day");
                            }
                            addToSet(monLdaySet.value, end, 1, day_of_month);
                        } catch (ParseException e) {
                            e.printStackTrace();
                            break;
                        }
                    }
                }
                sortedSet = daysOfMonth.tailSet(new Integer(dayOfMonth));
                if (lastdayOfMonth && !endDaysFlag) {
                    if (!nearestWeekday) {
                        if (monLdaySet != null && monLdaySet.isLast) {
                            try {
                                getSet(day_of_month).clear();
                                addToSet(endDays, -1, -1, day_of_month);
                                endDaysFlag = true;
                                continue;
                            } catch (ParseException e) {
                                e.printStackTrace();
                                break;
                            }
                        } else {
                            $ = dayOfMonth;
                            dayOfMonth = getDaySizeOfMonth(calendar1.get(Calendar.YEAR), month);
                        }
                    } else {
                        $ = dayOfMonth;
                        dayOfMonth = getDaySizeOfMonth(calendar1.get(Calendar.YEAR), month);

                        Calendar Calendar2 = Calendar.getInstance();
                        Calendar2.set(Calendar.SECOND, 0);
                        Calendar2.set(Calendar.MINUTE, 0);
                        Calendar2.set(Calendar.HOUR_OF_DAY, 0);
                        Calendar2.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                        Calendar2.set(Calendar.MONTH, month - 1);
                        Calendar2.set(Calendar.YEAR, calendar1.get(Calendar.YEAR));

                        int ldom = getDaySizeOfMonth(calendar1.get(Calendar.YEAR), month);
                        int dow = Calendar2.get(Calendar.DAY_OF_WEEK);

                        if (dow == Calendar.SATURDAY && dayOfMonth == 1) {
                            dayOfMonth += 2;
                        } else if (dow == Calendar.SATURDAY) {
                            dayOfMonth -= 1;
                        } else if (dow == Calendar.SUNDAY && dayOfMonth == ldom) {
                            dayOfMonth -= 2;
                        } else if (dow == Calendar.SUNDAY) {
                            dayOfMonth += 1;
                        }

                        Calendar2.set(Calendar.SECOND, second);
                        Calendar2.set(Calendar.MINUTE, minute);
                        Calendar2.set(Calendar.HOUR_OF_DAY, hourOfDay);
                        Calendar2.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                        Calendar2.set(Calendar.MONTH, month - 1);
                        Date nTime = Calendar2.getTime();
                        if (nTime.before(afterTime)) {
                            dayOfMonth = 1;
                            month++;
                        }
                    }
                } else if (nearestWeekday) {
                    $ = dayOfMonth;
                    dayOfMonth = ((Integer) daysOfMonth.first()).intValue();

                    Calendar calendar = Calendar.getInstance();
                    calendar.set(Calendar.SECOND, 0);
                    calendar.set(Calendar.MINUTE, 0);
                    calendar.set(Calendar.HOUR_OF_DAY, 0);
                    calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                    calendar.set(Calendar.MONTH, month - 1);
                    calendar.set(Calendar.YEAR, calendar1.get(Calendar.YEAR));

                    int ldom = getDaySizeOfMonth(calendar1.get(Calendar.YEAR), month);
                    int dow = calendar.get(Calendar.DAY_OF_WEEK);

                    if (dow == Calendar.SATURDAY && dayOfMonth == 1) {
                        dayOfMonth += 2;
                    } else if (dow == Calendar.SATURDAY) {
                        dayOfMonth -= 1;
                    } else if (dow == Calendar.SUNDAY && dayOfMonth == ldom) {
                        dayOfMonth -= 2;
                    } else if (dow == Calendar.SUNDAY) {
                        dayOfMonth += 1;
                    }

                    calendar.set(Calendar.SECOND, second);
                    calendar.set(Calendar.MINUTE, minute);
                    calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                    calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                    calendar.set(Calendar.MONTH, month - 1);
                    Date nTime = calendar.getTime();
                    if (nTime.before(afterTime)) {
                        dayOfMonth = ((Integer) daysOfMonth.first()).intValue();
                        month++;
                    }
                } else if (sortedSet != null && sortedSet.size() != 0) {
                    $ = dayOfMonth;
                    dayOfMonth = ((Integer) sortedSet.first()).intValue();
                    // make sure we don't over-run a short month, such as february
                    int lastDay = getDaySizeOfMonth(calendar1.get(Calendar.YEAR), month);
                    if (dayOfMonth > lastDay) {
                        dayOfMonth = ((Integer) daysOfMonth.first()).intValue();
                        month++;
                    }
                } else {
                    dayOfMonth = ((Integer) daysOfMonth.first()).intValue();
                    month++;
                    endDaysFlag = false;
                }

                if (dayOfMonth != $ || month != tmon) {
                    calendar1.set(Calendar.SECOND, 0);
                    calendar1.set(Calendar.MINUTE, 0);
                    calendar1.set(Calendar.HOUR_OF_DAY, 0);
                    calendar1.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                    calendar1.set(Calendar.MONTH, month - 1);
                    // '- 1' because calendar is 0-based for this field, and we
                    // are 1-based
                    continue;
                }
            } else if (dayOfWSpec && !dayOfMSpec) { // get day by day of week rule
                if (lastdayOfWeek) { // are we looking for the last XXX day of
                    // the month?
                    int dow = ((Integer) daysOfWeek.first()).intValue(); // desired
                    // d-o-w
                    int cDow = calendar1.get(Calendar.DAY_OF_WEEK); // current d-o-w
                    int daysToAdd = 0;
                    if (cDow < dow) {
                        daysToAdd = dow - cDow;
                    }
                    if (cDow > dow) {
                        daysToAdd = dow + (7 - cDow);
                    }

                    int lDay = getDaySizeOfMonth(calendar1.get(Calendar.YEAR), month);

                    if (dayOfMonth + daysToAdd > lDay) { // did we already miss the
                        // last one?
                        calendar1.set(Calendar.SECOND, 0);
                        calendar1.set(Calendar.MINUTE, 0);
                        calendar1.set(Calendar.HOUR_OF_DAY, 0);
                        calendar1.set(Calendar.DAY_OF_MONTH, 1);
                        calendar1.set(Calendar.MONTH, month);
                        // no '- 1' here because we are promoting the month
                        continue;
                    }

                    // find date of last occurance of this day in this month...
                    while ((dayOfMonth + daysToAdd + 7) <= lDay) {
                        daysToAdd += 7;
                    }

                    dayOfMonth += daysToAdd;

                    if (daysToAdd > 0) {
                        calendar1.set(Calendar.SECOND, 0);
                        calendar1.set(Calendar.MINUTE, 0);
                        calendar1.set(Calendar.HOUR_OF_DAY, 0);
                        calendar1.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                        calendar1.set(Calendar.MONTH, month - 1);
                        // '- 1' here because we are not promoting the month
                        continue;
                    }

                } else if (nthdayOfWeek != 0) {
                    // are we looking for the Nth XXX day in the month?
                    int dow = ((Integer) daysOfWeek.first()).intValue(); // desired
                    // d-o-w
                    int cDow = calendar1.get(Calendar.DAY_OF_WEEK); // current d-o-w
                    int daysToAdd = 0;
                    if (cDow < dow) {
                        daysToAdd = dow - cDow;
                    } else if (cDow > dow) {
                        daysToAdd = dow + (7 - cDow);
                    }

                    boolean dayShifted = false;
                    if (daysToAdd > 0) {
                        dayShifted = true;
                    }

                    dayOfMonth += daysToAdd;
                    int weekOfMonth = dayOfMonth / 7;
                    if (dayOfMonth % 7 > 0) {
                        weekOfMonth++;
                    }

                    daysToAdd = (nthdayOfWeek - weekOfMonth) * 7;
                    dayOfMonth += daysToAdd;
                    if (daysToAdd < 0
                            || dayOfMonth > getDaySizeOfMonth(calendar1
                            .get(Calendar.YEAR), month)) {
                        calendar1.set(Calendar.SECOND, 0);
                        calendar1.set(Calendar.MINUTE, 0);
                        calendar1.set(Calendar.HOUR_OF_DAY, 0);
                        calendar1.set(Calendar.DAY_OF_MONTH, 1);
                        calendar1.set(Calendar.MONTH, month);
                        // no '- 1' here because we are promoting the month
                        continue;
                    } else if (daysToAdd > 0 || dayShifted) {
                        calendar1.set(Calendar.SECOND, 0);
                        calendar1.set(Calendar.MINUTE, 0);
                        calendar1.set(Calendar.HOUR_OF_DAY, 0);
                        calendar1.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                        calendar1.set(Calendar.MONTH, month - 1);
                        // '- 1' here because we are NOT promoting the month
                        continue;
                    }
                } else {
                    int cDow = calendar1.get(Calendar.DAY_OF_WEEK); // current d-o-w
                    int dow = ((Integer) daysOfWeek.first()).intValue(); // desired
                    // d-o-w
                    sortedSet = daysOfWeek.tailSet(new Integer(cDow));
                    if (sortedSet != null && sortedSet.size() > 0) {
                        dow = ((Integer) sortedSet.first()).intValue();
                    }

                    int daysToAdd = 0;
                    if (cDow < dow) {
                        daysToAdd = dow - cDow;
                    }
                    if (cDow > dow) {
                        daysToAdd = dow + (7 - cDow);
                    }

                    int lDay = getDaySizeOfMonth(calendar1.get(Calendar.YEAR), month);

                    if (dayOfMonth + daysToAdd > lDay) { // will we pass the end of
                        // the month?
                        calendar1.set(Calendar.SECOND, 0);
                        calendar1.set(Calendar.MINUTE, 0);
                        calendar1.set(Calendar.HOUR_OF_DAY, 0);
                        calendar1.set(Calendar.DAY_OF_MONTH, 1);
                        calendar1.set(Calendar.MONTH, month);
                        // no '- 1' here because we are promoting the month
                        continue;
                    } else if (daysToAdd > 0) { // are we swithing days?
                        calendar1.set(Calendar.SECOND, 0);
                        calendar1.set(Calendar.MINUTE, 0);
                        calendar1.set(Calendar.HOUR_OF_DAY, 0);
                        calendar1.set(Calendar.DAY_OF_MONTH, dayOfMonth + daysToAdd);
                        calendar1.set(Calendar.MONTH, month - 1);
                        // '- 1' because calendar is 0-based for this field,
                        // and we are 1-based
                        continue;
                    }
                }
            } else { // dayOfWSpec && !dayOfMSpec
                throw new UnsupportedOperationException(
                        "Support for specifying both a day-of-week AND a day-of-month $parameter is not implemented.");
                // TODO:
            }
            calendar1.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            month = calendar1.get(Calendar.MONTH) + 1;
            // '+ 1' because calendar is 0-based for this field, and we are
            // 1-based
            int year = calendar1.get(Calendar.YEAR);
            $ = -1;

            // test for expressions that never generate a valid fire date,
            // but keep looping...
            if (year > crontrigger_year_to_giveup_scheduling_at) {
                return null;
            }

            // get month...................................................
            sortedSet = months.tailSet(new Integer(month));
            if (sortedSet != null && sortedSet.size() != 0) {
                $ = month;
                month = ((Integer) sortedSet.first()).intValue();
            } else {
                month = ((Integer) months.first()).intValue();
                year++;
            }
            if (month != $) {
                calendar1.set(Calendar.SECOND, 0);
                calendar1.set(Calendar.MINUTE, 0);
                calendar1.set(Calendar.HOUR_OF_DAY, 0);
                calendar1.set(Calendar.DAY_OF_MONTH, 1);
                calendar1.set(Calendar.MONTH, month - 1);
                // '- 1' because calendar is 0-based for this field, and we are
                // 1-based
                calendar1.set(Calendar.YEAR, year);
                continue;
            }
            calendar1.set(Calendar.MONTH, month - 1);
            // '- 1' because calendar is 0-based for this field, and we are
            // 1-based

            year = calendar1.get(Calendar.YEAR);
            $ = -1;

            // get year...................................................
            sortedSet = years.tailSet(new Integer(year));
            if (sortedSet != null && sortedSet.size() != 0) {
                $ = year;
                year = ((Integer) sortedSet.first()).intValue();
            } else {
                return null; // ran out of years...
            }

            if (year != $) {
                calendar1.set(Calendar.SECOND, 0);
                calendar1.set(Calendar.MINUTE, 0);
                calendar1.set(Calendar.HOUR_OF_DAY, 0);
                calendar1.set(Calendar.DAY_OF_MONTH, 1);
                calendar1.set(Calendar.MONTH, 0);
                // '- 1' because calendar is 0-based for this field, and we are
                // 1-based
                calendar1.set(Calendar.YEAR, year);
                continue;
            }
            calendar1.set(Calendar.YEAR, year);

            gotOne = true;
        } // while( !done )

        return calendar1.getTime();
    }

    /**
     * Advance the calendar to the particular hour paying particular attention
     * to daylight saving problems.
     */
    protected void setCalendarHour(Calendar calendar, int hour) {
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        if (calendar.get(Calendar.HOUR_OF_DAY) != hour && hour != 24) {
            calendar.set(Calendar.HOUR_OF_DAY, hour + 1);
        }
    }

    /**
     * 获取一个月多少天
     */
    protected int getDaySizeOfMonth(int year, int month) {

        switch (month) {
            case 1:
                return 31;
            case 2:
                return (isLeapYear(year)) ? 29 : 28;
            case 3:
                return 31;
            case 4:
                return 30;
            case 5:
                return 31;
            case 6:
                return 30;
            case 7:
                return 31;
            case 8:
                return 31;
            case 9:
                return 30;
            case 10:
                return 31;
            case 11:
                return 30;
            case 12:
                return 31;
            default:
                throw new IllegalArgumentException("Illegal month number: "
                        + month);
        }
    }

    /**
     * 判断是否是闰年
     */
    protected boolean isLeapYear(int year) {
        return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
    }

}

